package com.android.clinic.doctors.app.glide;

import android.graphics.BitmapFactory;

/**
 * Created by cheng on 2018/6/19.
 */
public class BitmapUtils {

    /**
     *
     * 计算inSampleSize
     BitmapFactory.Options newOpts =  new  BitmapFactory.Options();
     newOpts.inJustDecodeBounds = true;
     ByteArrayOutputStream out = new ByteArrayOutputStream();
     resource.compress(Bitmap.CompressFormat.JPEG, 100, out); //图片过大内存溢出
     ByteArrayInputStream isBm =  new  ByteArrayInputStream(out.toByteArray());
     decodeStream(isBm, null, newOpts);
     newOpts.inSampleSize = calculateInSampleSize(newOpts, imageView.getWidth(), imageView.getHeight());
     Bitmap bitmap = decodeStream(isBm, null, newOpts);
     imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
     * @param oldwidth
     * @param oldheight
     * @param reqWidth
     * @param reqHeight
     * @return
     */
    public static int calculateInSampleSize(int oldwidth, int oldheight, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = oldheight;
        final int width = oldwidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            if (width > height) {
                inSampleSize = Math.round((float) height / (float) reqHeight);
            } else {
                inSampleSize = Math.round((float) width / (float) reqWidth);
            }

            final float totalPixels = width * height;

            // Anything more than 2x the requested pixels we'll sample down
            // further.
            // 任何超过2倍的请求像素，我们将品尝简化
            // 更多。
            final float totalReqPixelsCap = reqWidth * reqHeight * 2;

            while (totalPixels / (inSampleSize * inSampleSize) > totalReqPixelsCap) {
                inSampleSize++;
            }
        }
        return inSampleSize;
    }

    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        return calculateInSampleSize(options.outWidth, options.outHeight, reqWidth, reqHeight);
    }

}
